package net.qiqbframework.modelling.command.voucher;

import net.qiqbframework.common.utils.StringUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.util.Optional;

public class FieldBizIdentifierVoucherModel<ID, C> implements BizIdentifierVoucherModel<ID, C> {

    private final Field field;

    private final Class<ID> bizIdDeclaredType;


    private final String routingBizIdentifierName;

    public FieldBizIdentifierVoucherModel(Field field) {
        this(field, null);
    }

    public FieldBizIdentifierVoucherModel(Field field, String routingBizIdentifierName) {
        this.field = field;
        this.bizIdDeclaredType = (Class<ID>) this.field.getDeclaringClass();
        this.routingBizIdentifierName = StringUtil.isEmpty(routingBizIdentifierName) ? field.getName() : routingBizIdentifierName;
    }

    @Override
    public Class<ID> declaredType() {
        return bizIdDeclaredType;
    }

    @Override
    public Member member() {
        return field;
    }

    @Override
    public String routingBizIdentifierName() {
        return routingBizIdentifierName;
    }

    @Override
    public Optional<ID> bizIdentifierVoucher(C command) {
        try {
            final Object val = field.get(command);
            if (val != null) {
                return Optional.of((ID) val);
            }
            return Optional.empty();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public int priority() {
        return 0;
    }
}
